package com.mini.handler;

import com.mini.MiniResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;

public class MiniScalarHandler<T> implements MiniResultSetHandler<T> {

    // 要检索的列号
    private final int columnIndex;
    // 要检索的列名
    private final String columnName;

    // 定义构造函数初始化最终变量
    public MiniScalarHandler() {
        this(1, null);
    }
    public MiniScalarHandler(int columnIndex, String columnName) {
        this.columnIndex = columnIndex;
        this.columnName = columnName;
    }
    public MiniScalarHandler(int columnIndex) {
        this(columnIndex,null);
    }
    public MiniScalarHandler(String columnName) {
        this(1,columnName);
    }

    @Override
    public T handle(ResultSet resultSet) throws SQLException {
        // 返回第一行第一列（或指定列名）的值；一般用于聚合函数的查询结果
        if (resultSet.next()) {
            if (this.columnName == null) {
                return (T) resultSet.getObject(this.columnIndex);
            }
            return (T) resultSet.getObject(this.columnName);
        }
        return null;
    }
}
